
var MIME = {
  "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "htm": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml",
  "txt": "text/plain"
};

function getType(file)
{
	try
	{
		var arr = file.split(".");
		return MIME[arr[arr.length-1] || "txt"] || "text/plain";
	}
	catch(e)
	{
		console.log(e);
		return "text/plain";
	}
}

var fs = require('fs');
function sendFile(file, rsp) 
{
	try
	{
		var data = fs.readFileSync(file);
		rsp.writeHead(200, {'Content-Type': getType(file)});
		rsp.write(data);
	}
	catch(e)
	{
		rsp.writeHead(404, {'Content-Type': "text/plain"});
		rsp.write(e.toString());
	}

	rsp.end();
}

function sendDir(dir, rsp)
{
	var exec = require('child_process').exec;
	var path = require('path');

	var child = exec("dir /B /S *.htm?", {cwd: dir, encoding:'binary'},
		function (error, stdout, stderr)
		{
			var arr = stdout.split(/[\r\n]+/mg);
			
			for (var i in arr)
			{
				arr[i] = path.relative(dir, arr[i]);
			}
			arr.unshift(path.resolve(dir));
			
			rsp.writeHead(200, {'Content-Type': "application/json"});
			
			var StringDecoder = require('string_decoder').StringDecoder;
			var decoder = new StringDecoder('utf8');
			
			rsp.write(decoder.write(arr.join("\r\n")));
			rsp.end();
		}
	);
}

var url = require("url");
var APP_ROOT = "../WebApps";
function server(req, rsp)
{
	var addr = url.parse(req.url);
	
	if (addr.query && (addr.query.length > 0))
	{
		return;
	}
	
	if ('/' == addr.pathname.charAt(addr.pathname.length - 1))
	{
		sendDir(APP_ROOT + addr.pathname, rsp)
	}
	else
	{
		sendFile(APP_ROOT + addr.pathname, rsp) 
	}
}

var http = require('http');
http.createServer(server).listen(9999);
